iT邦幫忙

2021 iThome 鐵人賽

DAY 17
1
AI & Data

機器學習與前端網頁系列 第 17

Day 17 LeetCode 322. Coin Change

  • 分享至 

  • xImage
  •  

換個口味來寫 LeetCode,並且挑戰一下不太擅長的動態規劃。

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Example 3:

Input: coins = [1], amount = 0
Output: 0

Example 4:

Input: coins = [1], amount = 1
Output: 1

Example 5:

Input: coins = [1], amount = 2
Output: 2
class Solution:

    def solve(self, coins: List[int], amount: int):

        box = [amount+1 for i in range((amount + 1))]
        box[0] = 0
        for i in range(1, amount + 1):
            for coin in coins:

                if coin <= i:
                    box[i] = min(box[i], box[i - coin] + 1)


        return -1 if box[amount] > amount else box[amount]
        pass

    def coinChange(self, coins: List[int], amount: int) -> int:

        if amount == 0:
            return 0

        return self.solve(coins, amount)

在這一題中最重要的就是 11 行的 box[i - coin] + 1,他代表繼承之前的硬幣數。

比如說現在要找總合 i == 10 的,當 coin == 3 時,
會找 box[7] 的硬幣數並+1,
因為任何一組能構成總和 7 的硬幣,只要加這一枚硬幣 3 總和就是 10。


上一篇
Day 16 ml5.js
下一篇
Day 18 ml5.js-2
系列文
機器學習與前端網頁30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言